package myJs.common

import com.softwaremill.quicklens._
import myJs.Implicits._
import myJs.MyPages
import myJs.api.Api
import myJs.common.loadSample.LabCp
import myJs.cps.{ImageSelectCp, PureDatePickerCp, Style}
import myJs.myPkg._
import myJs.myPkg.highcharts._
import myJs.myPkg.reactHookForm.{ReactHookForm, UseFormOptions}
import myJs.tool.Tool
import org.scalajs.dom.{File, FormData, URLSearchParams, html}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.FreezerSet.FreezerSetData
import shared.pojo.Pojo.ValidData
import shared.pojo.Sample._
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.{Fragment, React}
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.web.html._
import upickle.default._

import scala.scalajs.js
import scala.scalajs.js.JSON

/**
 * Created by yz on 21/1/2022
 */
@react object FreezerViewCp {

  case class Props(
                    viewSamplePage: MyPages
                  )

  val component = FunctionalComponent[Props] { props =>

    val (sampleId, setSampleId) = useState("")
    val (freezerNumber, setFreezerNumber) = useState("1")
    val (freezerLayerNumber, setFreezerLayerNumber) = useState("1")
    val (sampleIdSame, setSampleIdSame) = useState(false)

    val aRef = React.createRef[html.Link]

    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange"))

    object FTool {

      def freezerNumberChange = (v: String) => {
        setFreezerNumber(v)
      }

      def freezerLayerNumberChange = (v: String) => {
        setFreezerLayerNumber(v)
      }

      def clickFn = (e: Event) => {
        setSampleIdSame(false)
        val point = e.point
        if (point.value > 0) {
          val curSampleId = point.custom.sampleId
          setSampleId((x) => {
            setSampleIdSame(curSampleId == x)
            curSampleId
          })
        }
        ()
      }

      def refreshSvg = () => {
        val options = Tool.layerOptions.copy(shade = List("0.1", "#fff"))
        val index = layer.load(0, options)
        val request = FreezerInfo(freezerNumber = freezerNumber, freezerLayerNumber = freezerLayerNumber)
        Api.sample.freezerInfo(request).zip(Api.freezerSet.get(FreezerSetData(freezerNumber = freezerNumber,
          freezerLayerNumber = freezerLayerNumber))).map { case (response, freezerSetOp) =>
          val responseMap = response.map { x =>
            (x.x, x.y) -> x
          }.toMap
          val freezerSet = freezerSetOp.getOrElse(FreezerSetData())
          val xs = (1 to freezerSet.totalRowNumber.toInt).toList
          val ys = (1 to freezerSet.totalColNumber.toInt).toList
          val xCategories = xs.map { x =>
            x.toString
          }
          val yCategories = ys.map { x =>
            x.toString
          }
          val datas = xs.flatMap { x =>
            ys.map { y =>
              responseMap.get((x, y)).map { rp =>
                val customData = CustomData(updateTime = rp.updateTime, sampleId = rp.sampleId)
                HeatmapData(x = x - 1, y = y - 1, value = 1, custom = customData, className = "clickable",
                  color = "#F46160")
              }.getOrElse {
                HeatmapData(x = x - 1, y = y - 1, value = 0, name = s"${x}${y}", color = "#B4E788")
              }
            }
          }

          def formatterFn: js.ThisFunction0[FormatterData, js.Any] = (data: FormatterData) => {
            val point = data.point
            if (point.value > 0) {
              s"样本编号:${point.custom.sampleId}<br>行数:${point.x + 1}<br>列数:${point.y + 1}<br>更新时间:${point.custom.updateTime}"
            } else {
              false
            }: js.Any
          }

          val options = HighchartsOptions(
            chart = Chart(
              `type` = "heatmap",
              plotBorderWidth = 0,
              height = 1000,
              width = 1000,
            ),
            title = Title(
              text = ""
            ),
            legend = Legend(
              enabled = false
            ),
            xAxis = XAxis(
              categories = xCategories,
              opposite = true,
              title = Title(
                text = ""
              ),
              labels = Labels(
                step = 1
              )
            ),
            yAxis = YAxis(
              categories = yCategories,
              title = Title(
                text = ""
              ),
              reversed = true
            ),
            tooltip = Tooltip(
              formatter = formatterFn
            ),
            series = List(
              Heatmap(
                name = "Heat",
                borderWidth = 1,
                borderColor = "#ffffff",
                turboThreshold = 0,
                data = datas,
                dataLabels = DataLabels(
                  enabled = false,
                  color = "#000000"
                )
              ),
            ),
            credits = Credits(enabled = false),
            plotOptions = PlotOptions(
              series = SeriesOption(
                point = Point(
                  events = Events(
                    click = clickFn,
                  )
                )
              )
            )
          )
          Highcharts.chart("plotSvg", options = options)
        }
        layer.close(index)
        ()
      }


    }

    useEffect(() => {
      FTool.refreshSvg()
    }, List()
    )

    useEffect(() => {
      if (sampleId.nonBlank) {
        aRef.current.click()
      }
    }, List(sampleId)
    )

    useEffect(() => {
      if (sampleIdSame) {
        aRef.current.click()
      }
    }, List(sampleIdSame)
    )

    Fragment(
      form(className := "form-horizontal", id := "form", onSubmit := {
        useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
          println(JSON.stringify(data))
          FTool.refreshSvg()
        })
      },

        div(className := "form-group",
          label(className := "control-label col-sm-2", "冰箱编号:"),
          div(className := "col-sm-4",
            PureRSelectCp(useForm = useForm, name = "freezerNumber", value = freezerNumber,
              onChange = FTool.freezerNumberChange, optionMap = Tool.freezerNumberMap
            )
          ),
          label(className := "control-label col-sm-2", "层数:"),
          div(className := "col-sm-4",
            PureRSelectCp(useForm = useForm, name = "freezerLayerNumber", value = freezerLayerNumber,
              onChange = FTool.freezerLayerNumberChange, optionMap = Tool.freezerLayerNumberMap
            )
          )
        ),

        div(className := "form-group",
          div(className := "actions col-sm-offset-2 col-sm-2",
            button(`type` := "submit", className := "btn btn-primary",
              s" 查看",
            ),
          )
        ),
      ),
      div(className := "mySvg", id := "plotSvg", style := Style(width = "100%")),
      a(href := s"${props.viewSamplePage.absolutePath}?id=${sampleId}", target := "_blank", ref := aRef)
    )


  }


}
